import redis
from dynaconf import Dynaconf

# 加载配置
settings = Dynaconf(
    settings_files=['config/config.yaml'],
    environments=True
)

# Redis 连接池
redis_pool = redis.ConnectionPool(
    host=settings.redis.host,
    port=settings.redis.port,
    db=settings.redis.db,
    password=settings.redis.password if settings.redis.password else None,
    decode_responses=True  # 自动将响应解码为字符串
)

class RedisUtil:
    """Redis 工具类，封装常用的 Redis 操作"""
    
    @staticmethod
    def get_conn():
        """获取一个 Redis 连接"""
        return redis.Redis(connection_pool=redis_pool)
    
    @staticmethod
    def set(key: str, value: str, expire: int = None):
        """设置键值对
        
        Args:
            key: Redis键
            value: 值
            expire: 过期时间(秒)
        """
        conn = RedisUtil.get_conn()
        conn.set(key, value)
        if expire:
            conn.expire(key, expire)
            
    @staticmethod
    def get(key: str) -> str:
        """获取值
        
        Args:
            key: Redis键
            
        Returns:
            str: 值，不存在返回None
        """
        conn = RedisUtil.get_conn()
        return conn.get(key)
    
    @staticmethod
    def delete(key: str) -> int:
        """删除键
        
        Args:
            key: Redis键
            
        Returns:
            int: 删除的键数量
        """
        conn = RedisUtil.get_conn()
        return conn.delete(key)
    
    @staticmethod
    def exists(key: str) -> bool:
        """检查键是否存在
        
        Args:
            key: Redis键
            
        Returns:
            bool: 是否存在
        """
        conn = RedisUtil.get_conn()
        return conn.exists(key) > 0
